package jrdcom.com.onecodesample.Util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.spec.ECField;

/**
 * Created by dhcui on 2017/1/17.
 */
public class HttpUtil {
    public interface HttpCallbackListener{
        void onFinish(String response);
        void onError(Exception e);
    }

    public static void sendHttpRequest(final String address, final HttpCallbackListener listener){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection =  null;
                try{
                    URL url = new URL(address);
                    connection = (HttpURLConnection)url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setReadTimeout(8000);
                    connection.setConnectTimeout(8000);
                    //获取一个buffer reader
                    InputStream in = connection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line = null;
                    while((line = bufferedReader.readLine())!=null){
                        stringBuilder.append(line);
                    }
                    if(listener !=null){
                        listener.onFinish(stringBuilder.toString());
                    }
                }catch (Exception e){
                    listener.onError(e);
                }finally {

                }

            }
        }).start();

    }

}
